package com.hwtx.form.domain.handle.formconfig;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hwtx.form.annotation.Action;
import com.hwtx.form.annotation.FormType;
import com.hwtx.form.annotation.Log;
import com.hwtx.form.annotation.OperationType;
import com.hwtx.form.domain.FormConstants;
import com.hwtx.form.domain.def.*;
import com.hwtx.form.domain.def.meta.config.FormComponentConfig;
import com.hwtx.form.domain.handle.FormDataHandle;
import com.hwtx.form.domain.handle.core.DefaultFormDataHandle;
import com.hwtx.form.domain.handle.core.DefaultFormDataReadHandle;
import com.hwtx.form.domain.handle.datamodel.DataModel;
import com.hwtx.form.domain.handle.datamodel.DataModelDetail;
import com.hwtx.form.domain.handle.i18n.I18nConfig;
import com.hwtx.form.domain.repo.DataModelRepo;
import com.hwtx.form.domain.repo.FormConfigRepo;
import com.hwtx.form.domain.repo.FormRepo;
import com.hwtx.form.domain.service.CommonApiInvoker;
import com.hwtx.form.domain.vo.*;
import com.hwtx.form.dto.FormDefDto;
import com.hwtx.form.dto.FormQuery;
import com.hwtx.form.persistence.entity.FormConfigQuery;
import com.hwtx.form.persistence.entity.FormDefDetail;
import com.hwtx.form.util.FormUtil;
import com.hwtx.form.util.JacksonUtil;
import com.hwtx.form.util.StrUtil;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.system.vo.AmisTableData;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static com.hwtx.form.domain.FormConstants.FORM_ID;
import static com.hwtx.form.domain.FormConstants.FormLayout.LAYOUT_0;
import static com.hwtx.form.domain.FormConstants.SHORT_FORM_ID;
import static com.hwtx.form.domain.def.meta.config.FormComponentConfig.getFormComponentConfig;
import static com.hwtx.form.util.FormUtil.*;
import static com.hwtx.form.util.JacksonUtil.*;
import static io.geekidea.boot.generator.constant.GeneratorConstant.COMMON_EXCLUDE_FIELDS;

@Slf4j
@Component
public class FormConfigAction {

    @Resource
    private FormConfigRepo formConfigRepo;
    @Resource
    private FormRepo formRepo;
    @Resource
    private DataModelRepo dataModelRepo;
    @Resource
    private FormConfigDataHandle formConfigDataHandle;
    @Resource
    private DefaultFormDataHandle defaultFormDataHandle;
    @Resource
    private DefaultFormDataReadHandle defaultFormDataReadHandle;
    @Resource
    private I18nConfig i18nConfig;
    @Resource
    private FormTplHandle formTplHandle;

    private static FormConfigExt.@NotNull FormConfigCtr getFormConfigCtr(String type, FormConfigExt formConfigExt) {
        FormConfigExt.FormConfigCtr formConfigCtr = null;
        switch (type) {
            case FormConstants.FORM -> {
                FormConfigExt.FormConfig formConfig = formConfigExt.getForm();
                if (formConfig == null) {
                    formConfig = new FormConfigExt.FormConfig();
                    formConfigExt.setForm(formConfig);
                }
                formConfigCtr = formConfig.getConfigCtr();
                if (formConfigCtr == null) {
                    formConfigCtr = new FormConfigExt.FormConfigCtr();
                    formConfig.setConfigCtr(formConfigCtr);
                }
            }
            case FormConstants.LIST -> {
                FormConfigExt.ListConfig listConfig = formConfigExt.getList();
                if (listConfig == null) {
                    listConfig = new FormConfigExt.ListConfig();
                    formConfigExt.setList(listConfig);
                }
                formConfigCtr = listConfig.getConfigCtr();
                if (formConfigCtr == null) {
                    formConfigCtr = new FormConfigExt.FormConfigCtr();
                    listConfig.setConfigCtr(formConfigCtr);
                }
            }
            case FormConstants.QUERY -> {
                FormConfigExt.QueryConfig queryConfig = formConfigExt.getQuery();
                if (queryConfig == null) {
                    queryConfig = new FormConfigExt.QueryConfig();
                    formConfigExt.setQuery(queryConfig);
                }
                formConfigCtr = queryConfig.getConfigCtr();
                if (formConfigCtr == null) {
                    formConfigCtr = new FormConfigExt.FormConfigCtr();
                    queryConfig.setConfigCtr(formConfigCtr);
                }
            }
        }
        if (formConfigCtr == null) {
            formConfigCtr = new FormConfigExt.FormConfigCtr();
        }
        return formConfigCtr;
    }

    @Action
    @Log(type = OperationType.UPDATE, value = "服务输出参数数量")
    public int serviceOutputSize(Map<String, Object> formData) {
        FormComponentConfig formComponentConfig = getFormComponentConfig(formData);
        if (formComponentConfig == null) {
            return -1;
        }
        String code = getStrPostValue(formData, "apiCode");
        return CommonApiInvoker.getOutputParamNames(FormUtil.getApiDef(code)).size();
    }

    @Action
    @Log(type = OperationType.UPDATE, value = "保存组件扩展配置")
    public boolean saveComExtConfig(Map<String, Object> formData) {
        String type = getStrPostValue(formData, "type");
        if (type == null) {
            throw new BusinessException("配置类型不能为空");
        }
        Long id = getLongPostValue(formData, "cId");
        if (id == null) {
            throw new BusinessException("组件属性保存前必须先保存表单明细项");
        }
        FormConfigQuery formConfigQuery = formConfigRepo.getFormConfigQuery(id);
        if (formConfigQuery == null) {
            throw new BusinessException("表单项不存在");
        }
        Integer controller = switch (type) {
            case FormConstants.FORM -> formConfigQuery.getFormController();
            case FormConstants.LIST -> formConfigQuery.getListController();
            case FormConstants.QUERY -> formConfigQuery.getQueryController();
            default -> null;
        };
        FormComponentConfig formComponentConfig = getFormComponentConfig(controller);
        if (formComponentConfig != null) {
            FormConfigExt formConfigExt = getFormConfigExt(formConfigQuery.getExt());
            if (formConfigExt == null) {
                formConfigExt = new FormConfigExt();
            }
            FormConfigExt.FormConfigCtr formConfigCtr = getFormConfigCtr(type, formConfigExt);
            Map<String, Object> comExt = formComponentConfig.comExt(formData);
            if (formConfigCtr.getComExt() != null) {
                formConfigCtr.getComExt().putAll(comExt);
            } else {
                formConfigCtr.setComExt(comExt);
            }
            formConfigQuery.setExt(JacksonUtil.object2json(formConfigExt));
            formConfigRepo.updateFormConfigQuery(formConfigQuery);
        }
        return true;
    }

    @Action
    @Log(type = OperationType.GET, value = "获取组件配置")
    public String loadControllerConfig(Map<String, Object> formData) {
        String type = getStrPostValue(formData, "type");
        if (StringUtils.isBlank(type)) {
            throw new BusinessException("配置类型不能为空");
        }

        FormComponentConfig formComponentConfig = getFormComponentConfig(formData);
        if (formComponentConfig == null) {
            return "{}";
        }
        return i18nConfig.handlePageI18n(formComponentConfig.getConfig(type, formData), getLocale(formData));
    }

    @Action
    @Log(type = OperationType.GET, value = "获取表单布局配置")
    public String loadTpl(Map<String, Object> formData) {
        return formTplHandle.loadTpl(formData);
    }

    @Action
    @Log(type = OperationType.GET, value = "获取组件配置")
    public String ctrlConfig(Map<String, Object> formData) {
        return formTplHandle.ctrlConfig(formData);
    }

    @Action("comment2Dict")
    @Log(type = OperationType.CREATE, value = "字段注解转化为字典")
    @Transactional
    public ResultVo comment2dict(Map<String, Object> formData) throws Exception {
        if (formData.get("id") == null) {
            return ResultVo.builder().success(false).msg("字段Id不能为空").data(-1).build();
        }
        Long id = Long.valueOf(formData.get("id").toString());
        Long dictFId = Long.valueOf(formData.get("dictFId").toString());
        FormConfigQuery formConfigQuery = formConfigRepo.getFormConfigQuery(id);
        if (StringUtils.isBlank(formConfigQuery.getDescription())) {
            return ResultVo.builder().success(false).msg("字段描述为空").data(-1).build();
        }
        String desc = formConfigQuery.getDescription();
        if ((desc.contains(";") || desc.contains("；")) && (desc.contains(":") || desc.contains("：")) && (desc.contains("->"))) {
            String remark;
            String kvDelimiter;
            int start = desc.indexOf(":");
            if (start > 0) {
                remark = desc.substring(0, start);
                desc = desc.substring(start + 1);
                kvDelimiter = ";";
            } else {
                start = desc.indexOf("：");
                if (start < 0) {
                    return ResultVo.builder().success(false).msg("字段描述格式不正确").data(-1).build();
                }
                remark = desc.substring(0, start);
                desc = desc.substring(start + 1);
                kvDelimiter = ";";
            }
            Map<String, String> dictKv = StrUtil.split(desc, "->", kvDelimiter);
            if (MapUtils.isEmpty(dictKv)) {
                return ResultVo.builder().success(false).msg("字段描述格式不正确,无法创建字典").data(-1).build();
            }
            FormDef formDef = formRepo.getFormDef(dictFId);
            Map<String, Object> data = Maps.newHashMap();
            data.put("label", remark);

            List<Map<String, Object>> ret = defaultFormDataReadHandle.getCommonFormData(formDef, data);
            if (CollectionUtils.isNotEmpty(ret)) {
                Map<String, Object> dict = ret.getFirst();
                return ResultVo.builder().success(true).msg("字典【" + remark + "】已存在").data(dict.get(FormConstants.DefaultColumn.id.name())).build();
            }
            data.clear();
            data.put("label", remark);
            data.put("code", formData.get("code"));
            data.put("remark", remark);
            data.put("pid", 0L);
            ResultVo resultVo = (ResultVo) defaultFormDataHandle.saveFormData(formDef, FormData.builder().data(data).build());
            if (!resultVo.isSuccess()) {
                return ResultVo.builder().success(false).msg("创建字典失败" + resultVo.getMsg()).data(-1).build();
            }
            Long dictId = (Long) resultVo.getData();
            AtomicLong sort = new AtomicLong(1);
            data.clear();
            dictKv.forEach((k, v) -> {
                data.put("label", v);
                data.put("code", k);
                data.put("remark", v);
                data.put("sort", sort.getAndIncrement());
                data.put("pid", dictId);
                try {
                    defaultFormDataHandle.saveFormData(formDef, FormData.builder().data(data).build());
                } catch (Exception e) {
                    log.error("字典【{}】创建失败", remark, e);
                }
            });
            return ResultVo.builder().success(true).msg("处理成功").data(dictId).build();
        } else {
            return ResultVo.builder().success(false).msg("字段描述格式不正确").data(-1).build();
        }
    }

    @Action("actionChain")
    @Log(type = OperationType.GET, value = "获取目标动作选项")
    public List<Select.Option> actionChain(Map<String, Object> formData) {
        String parentId = null;
        if (formData.get("parentId") != null && !formData.get("parentId").toString().isEmpty()) {
            parentId = formData.get("parentId").toString();
        }
        if (StringUtils.isBlank(parentId)) {
            return getFromHandles().values().stream().map(formHandle -> {
                FormType formType = formHandle.getClass().getAnnotation(FormType.class);
                if (formType == null) {
                    return null;
                }
                String name = formType.value();
                String comment = formType.comment();
                if (StringUtils.isBlank(comment)) {
                    return null;
                }
                Select.Option operation = new Select.Option();
                operation.setLabel(comment);
                operation.setValue(name);
                return operation;
            }).filter(Objects::nonNull).collect(Collectors.toList());
        } else {
            FormDataHandle formHandle = getFromHandles().get(parentId);
            if (formHandle == null) {
                return Lists.newArrayList();
            }
            return getHandleActionOptions(formHandle.getClass());
        }
    }

    @Action
    @Log(type = OperationType.GET, value = "获取list全部操作选项")
    public List<Select.Option> listOps(Map<String, Object> formData) {
        Long formId = Long.valueOf(formData.get(SHORT_FORM_ID).toString());
        FormDefDetail formDetail = formConfigRepo.getFormDetail(formId);
        if (formDetail != null) {
            List<FormDetailExt.Operation> ops = getFormDetailOperationExt(formDetail.getExt());
            if (ops != null) {
                List<String> exist = ops.stream().map(FormDetailExt.Operation::getValue).toList();
                return FormConstants.FormDetailOperation.option().stream().peek(option -> {
                    if (exist.contains(option.getValue()) && FormConstants.FormDetailOperation.of(option.getValue()).isSystem()) {
                        option.setDisabled(true);
                    }
                }).collect(Collectors.toList());
            }
        }
        return FormConstants.FormDetailOperation.option();
    }

    @Action
    @Log(type = OperationType.GET, value = "批量创建表单")
    @Transactional
    public ResultVo batSave(Map<String, Object> formData) {
        String configTabs = (String) formData.get("configTabs");

        if (StringUtils.isBlank(configTabs)) {
            throw new BusinessException("请选择表单配置类型");
        }
        FormDetailExt formDetailExt = new FormDetailExt();
        formDetailExt.setConfigTabs(configTabs);
        List<Integer> comingConfigs = Arrays.stream(configTabs.split(",")).map(Integer::parseInt).sorted(Comparator.comparing(Integer::valueOf)).toList();
        List<Map<String, Object>> formDetails = (List<Map<String, Object>>) formData.get("formDetails");
        formDetails.forEach(map -> {
            FormDefDetail formDefDetail = map2Oject(map, FormDefDetail.class);
            String modelName = (String) map.get("modelName");
            String formName = (String) map.get("formName");
            String formType = (String) map.get("formType");
            String meta = (String) map.get("meta");
            if (StringUtils.isBlank(modelName) || StringUtils.isBlank(formName) || StringUtils.isBlank(formType)) {
                throw new BusinessException("数据模型,表单名,表单类型不能为空");
            }
            if (formRepo.containsFormDef(formName)) {
                throw new BusinessException("表单名【" + formName + "】重复");
            }
            FormDefDto formDefDto = new FormDefDto();
            formDefDto.setName(formName);
            formDefDto.setType(formType);
            formDefDto.setContent("{\n  \"type\": \"page\",\n  \"meta\": {\n    \"title\": \"" + meta + "\"\n  }\n}");
            try {
                Long formId = formRepo.addFormDef(formDefDto);
                formDefDetail.setFormId(formId);
                FormDetailExt ext = new FormDetailExt();
                if (comingConfigs.contains(FormConstants.FormConfigType.FORM.getValue())) {
                    formDefDetail.setTpl(LAYOUT_0.getCode());
                    formDefDetail.setWidth("800");
                }
                ext.setConfigTabs(configTabs);
                formDefDetail.setExt(object2json(ext));
                formConfigRepo.saveFormDefDetail(formDefDetail);
                formConfigDataHandle.updateFormDefConfigStatus(formId);
                initFormQuery(formId, "", modelName, comingConfigs, detail -> false);
            } catch (Exception e) {
                throw new BusinessException(e.getMessage());
            }
        });
        return ResultVo.builder().success(true).msg("保存成功").build();
    }

    private void initFormQuery(Long formId, String table, String
            modelName, List<Integer> tabs, Predicate<DataModelDetail> filter) {
        List<DataModelDetail> details = dataModelRepo.getDetails(DataModelDetailQuery.builder().modelName(modelName).tableName(table).status(FormConstants.Status.VALID).build());
        for (DataModelDetail detail : details) {
            if (filter.test(detail)) {
                continue;
            }
            FormConfigQuery query = new FormConfigQuery();
            if (tabs.contains(FormConstants.FormConfigType.FORM.getValue())) {
                if (FormConstants.DefaultColumn.getDefaultColumns().contains(detail.getName()) || Objects.equals(detail.getName(), FormConstants.DefaultColumn.id.name())) {
                    query.setIsFormShow((byte) 0);
                    query.setIsRequired((byte) 0);
                } else {
                    query.setIsFormShow((byte) 1);
                    query.setIsRequired((byte) 1);
                }
                if (Objects.equals(detail.getName(), FormConstants.DefaultColumn.id.name())) {
                    query.setFormController(FormConstants.FormComponentType.FORM_COM_HIDDEN.getValue());
                }
            }
            if (tabs.contains(FormConstants.FormConfigType.LIST.getValue())) {
                if (FormConstants.DefaultColumn.getDefaultColumns().contains(detail.getName()) || Objects.equals(detail.getName(), FormConstants.DefaultColumn.id.name())) {
                    query.setIsListShow((byte) 0);
                    query.setIsListQuery((byte) 0);
                } else {
                    query.setIsListQuery((byte) 1);
                    query.setIsListShow((byte) 1);
                }
            }
            if (tabs.contains(FormConstants.FormConfigType.QUERY.getValue())) {
                if (FormConstants.DefaultColumn.getDefaultColumns().contains(detail.getName()) || Objects.equals(detail.getName(), FormConstants.DefaultColumn.id.name())) {
                    query.setIsQueryShow((byte) 0);
                } else {
                    query.setIsQueryShow((byte) 1);
                }
            }
            query.setModelDetailId(detail.getId());
            query.setFormId(formId);
            query.setNum(detail.getNum());
            query.setDescription(detail.getDescription());
            formConfigRepo.saveFormConfigQuery(query);
        }
    }

    @Action
    @Log(type = OperationType.GET, value = "获取可选的列表字段")
    public List<Select.Option> listFields(Map<String, Object> formData) {
        Long formId = Long.valueOf(formData.get(SHORT_FORM_ID).toString());
        List<FormConfigQueryVo> formConfigQueryList = formConfigRepo.listMergedFormConfig(FormConfigQuerySearchVo.builder().isListQuery((byte) 1).formId(formId).build());
        if (!formConfigQueryList.isEmpty()) {
            return formConfigQueryList.stream().map(item -> {
                Select.Option operation = new Select.Option();
                operation.setValue(item.getField());
                operation.setLabel(item.getField());
                return operation;
            }).collect(Collectors.toList());

        }
        return Lists.newArrayList();
    }

    @Action
    @Log(type = OperationType.GET, value = "获取列表扩展表单初始化数据")
    public Map<String, Object> initOpForm(Map<String, Object> formData) {
        Long formId = Long.valueOf(formData.get(SHORT_FORM_ID).toString());
        Map<String, Object> ret = Maps.newHashMap();
        if (formData.get("index") == null || StringUtils.isBlank(formData.get("index").toString())) {
            Map<String, Object> actionParams = Maps.newHashMap();
            actionParams.put("id", "${id}");
            actionParams.put(FORM_ID, formId);
            ret.put("actionParams", actionParams);
        }
        return ret;
    }

    @Action
    @Log(type = OperationType.GET, value = "获取已设置的列表配置扩展")
    public FormDetailExt.ListExt getListExt(Map<String, Object> formData) {
        Long formId = Long.valueOf(formData.get(SHORT_FORM_ID).toString());
        FormDefDetail formDetail = formConfigRepo.getFormDetail(formId);
        if (formDetail != null) {
            FormDetailExt formDetailExt = getFormDetailExt(formDetail.getExt());
            if (formDetailExt != null) {
                return formDetailExt.getListExt();
            }
        }
        return null;
    }

    @Action
    @Log(type = OperationType.UPDATE, value = "获取表单配置初始化数据")
    public Map<String, Object> init(Map<String, Object> formData) {
        Long formId = Long.valueOf(formData.get(SHORT_FORM_ID).toString());
        FormDefDetail formDetail = formConfigRepo.getFormDetail(formId);
        if (formDetail != null) {
            Map<String, Object> ret = object2Map(formDetail);
            ret.put("ret", true);
            ret.remove("ext");
            FormDetailExt formDetailExt = getFormDetailExt(formDetail.getExt());
            if (formDetailExt != null) {
                if (formDetailExt.getConfigTabs() != null) {
                    ret.put("configTabs", formDetailExt.getConfigTabs());
                    ret.put("select", Lists.newArrayList(formDetailExt.getConfigTabs().split(",")).getLast());
                }
            }
            ret = ret.entrySet().stream().filter(entry -> !COMMON_EXCLUDE_FIELDS.contains(entry.getKey()) && entry.getValue() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
            return ret;
        }
        return Maps.newHashMap();
    }

    @Action
    @Log(type = OperationType.GET, value = "获取已配置的数据源")
    public Select getSources() {
        Select select = new Select();
        select.setOptions(dataModelRepo.getDataModels(DataModelQuery.builder().build()).stream().map(dataModel -> {
            Select.Option option = new Select.Option();
            if (DataModel.isSqlModel(dataModel.getModelType())) {
                option.setLabel(dataModel.getName() + " (sql模型)");
            } else if (DataModel.isAggTableModel(dataModel.getTableType())) {
                option.setLabel(dataModel.getName() + " (聚合模型)");
            } else {
                option.setLabel(dataModel.getName() + " (数据模型)");
            }
            option.setValue(dataModel.getName());
            return option;
        }).collect(Collectors.toList()));
        return select;
    }

    @Action
    @Log(type = OperationType.GET, value = "获取分组表单列表-value=id+label")
    public Select.GroupSelect listValueMergedForms(Map<String, Object> formData) {
        return forms(formData, formProperties -> formProperties.getFormId() + "->" + formProperties.getName());
    }

    @Action
    @Log(type = OperationType.GET, value = "获取分组表单列表")
    public Select.GroupSelect listForms(Map<String, Object> formData) {
        return forms(formData, FormProperties::getName);
    }

    private Select.GroupSelect forms(Map<String, Object> formData, Function<FormProperties, String> supplier) {
        AtomicLong fId = new AtomicLong(-1);
        if (formData.get(SHORT_FORM_ID) != null && !formData.get(SHORT_FORM_ID).equals("")) {
            fId.set(Long.parseLong(formData.get(SHORT_FORM_ID).toString()));
        }
        Select.GroupSelect select = new Select.GroupSelect();
        List<FormProperties> forms = formRepo.listFormInfo(new FormQuery());
        Map<String, List<FormProperties>> byType = forms.stream().collect(Collectors.groupingBy(FormProperties::getType));
        select.setOptions(byType.entrySet().stream().map(entry -> {
            Select.GroupOption option = new Select.GroupOption();
            option.setLabel(entry.getKey());
            option.setChildren(entry.getValue().stream().map(formProperties -> {
                Select.Option child = new Select.Option();
                child.setLabel(formProperties.getName());
                child.setValue(supplier.apply(formProperties));
                if (Objects.equals(formProperties.getFormId(), fId.get())) {
                    child.setDisabled(true);
                }
                return child;
            }).collect(Collectors.toList()));
            return option;
        }).toList());
        return select;
    }

    @Action
    @Log(type = OperationType.UPDATE, value = "初始化表单查询字段")
    @Transactional
    public ResultVo initQuery(Map<String, Object> formData) {
        Object fId = formData.get(SHORT_FORM_ID);
        if (fId == null) {
            throw new BusinessException("表单ID不能为空");
        }
        Object modelName = formData.get("modelName");
        if (modelName == null || StringUtils.isBlank(modelName.toString())) {
            throw new BusinessException("模块名称不能为空");
        }
        Long formId = Long.valueOf(fId.toString());
        FormDefDetail formDefDetail = formConfigRepo.getFormDetail(formId);
        if (formDefDetail == null) {
            throw new BusinessException("请先保存表单配置");
        }
        List<DataModelDetail> details = dataModelRepo.getDetails(formDefDetail.getModelName(), FormConstants.Status.VALID);
        if (CollectionUtils.isEmpty(details)) {
            throw new BusinessException("数据源不存在");
        }
        if (!Objects.equals(formDefDetail.getModelName(), modelName.toString())) {
            return ResultVo.builder().success(false).msg("数据源名称已变更，请先保存").build();
        }

        List<Integer> formConfigTypeDetails = List.of();
        FormDetailExt formDetailExt = getFormDetailExt(formDefDetail.getExt());
        if (formDetailExt != null && formDetailExt.getConfigTabs() != null) {
            String[] tabs = formDetailExt.getConfigTabs().split(",");
            formConfigTypeDetails = Arrays.stream(tabs).map(Integer::valueOf).toList();
        }

        List<FormConfigQueryVo> formConfigQueryVos = formConfigRepo.listMergedFormConfig(FormConfigQuerySearchVo.builder().formId(formId).build());
        if (formConfigQueryVos.isEmpty()) {
            initFormQuery(formId, null, formDefDetail.getModelName(), formConfigTypeDetails, detail -> false);
        } else {
            if (formConfigQueryVos.size() != details.size()) {
                List<Integer> typeDetails = formConfigTypeDetails;
                formConfigQueryVos.stream().filter(vo -> StringUtils.isNotBlank(vo.getTableName())).collect(Collectors.groupingBy(FormConfigQueryVo::getTableName)).forEach((table, vos) -> {
                    Map<String, FormConfigQueryVo> existConfigItems = vos.stream().collect(Collectors.toMap(FormConfigQueryVo::getField, Function.identity()));
                    initFormQuery(formId, table, formDefDetail.getModelName(), typeDetails, detail -> existConfigItems.containsKey(detail.getName()));
                });
            }
        }
        return ResultVo.builder().success(true).build();
    }

    @Action
    @Log(type = OperationType.UPDATE, value = "获取表单与列表组件")
    public AmisTableData<FormConfigControllerVo> getFormAndListContr(Map<String, Object> formData) {
        Object fId = formData.get(SHORT_FORM_ID);
        if (fId == null) {
            throw new BusinessException("表单ID不能为空");
        }
        Long formId = Long.valueOf(fId.toString());
        List<FormConfigQueryVo> configs = formConfigRepo.listMergedFormConfig(FormConfigQuerySearchVo.builder().formId(formId).build());
        AmisTableData<FormConfigControllerVo> misTableData = new AmisTableData<>();
        misTableData.setRows(configs.stream().filter(config -> config.getFormController() != null).map(config -> {
            FormConstants.FormComponentType cType = FormConstants.FormComponentType.of(config.getFormController());
            if (cType == null) {
                return null;
            }
            FormConfigControllerVo formConfigControllerVo = new FormConfigControllerVo();
            formConfigControllerVo.setId(config.getId());
            formConfigControllerVo.setFId(formId);
            formConfigControllerVo.setDescription(config.getDescription());
            formConfigControllerVo.setFormController(cType.getDesc());
            if (config.getListController() != null) {
                cType = FormConstants.FormComponentType.of(config.getListController());
                if (cType != null) {
                    formConfigControllerVo.setListController(cType.getDesc());
                }
            }
            return formConfigControllerVo;
        }).filter(Objects::nonNull).collect(Collectors.toList()));
        return misTableData;
    }

    @Action
    @Log(type = OperationType.UPDATE, value = "同步表单与列表之间的组件")
    public ResultVo syncContr(Map<String, Object> formData) {
        String configs = getStrPostValue(formData, "configs");
        if (StringUtils.isBlank(configs)) {
            return ResultVo.builder().success(false).msg("请选择需要同步的配置项").build();
        }
        Arrays.stream(configs.split(",")).map(Long::valueOf).forEach(id -> {
            FormConfigQuery formConfigQuery = formConfigRepo.getFormConfigQuery(id);
            if (formConfigQuery == null) {
                return;
            }
            FormConstants.FormComponentType cType = FormConstants.FormComponentType.of(formConfigQuery.getFormController());
            if (cType == FormConstants.FormComponentType.FORM_COM_SINGLE_SELECT) {
                FormConfigExt formConfigExt = getFormConfigExt(formConfigQuery.getExt());
                if (formConfigExt != null) {
                    FormConfigExt.FormConfig formConfig = formConfigExt.getForm();
                    if (formConfig != null) {
                        FormConfigExt.ListConfig listConfig = formConfigExt.getList();
                        if (listConfig == null) {
                            listConfig = new FormConfigExt.ListConfig();
                        }
                        listConfig.setConfigCtr(formConfig.getConfigCtr());
                        formConfigExt.setList(listConfig);
                        formConfigQuery.setExt(object2json(formConfigExt));
                    }
                }
            }
            formConfigQuery.setListController(formConfigQuery.getFormController());
            formConfigRepo.updateFormConfigQuery(formConfigQuery);
        });
        return ResultVo.builder().success(true).build();
    }
}
